package socketinterface.requests;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ClientRequest {
	private Socket                 clientSocket = null;
	private DataInputStream   in = null;
	private DataOutputStream  out = null;
	
	public synchronized Socket getClientSocket() {
		while (clientSocket == null) {
			try {
				wait();
			} catch (InterruptedException e) {
				
			}
		}
		return clientSocket;
	}
	
	public synchronized void openClientSocket(String serverName, int portNumber) {
		try {
			clientSocket = new Socket(serverName, portNumber);
			in  = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
			out = new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
			//out = new DataOutputStream(clientSocket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		notifyAll();
	}
	
	public synchronized void closeClientSocket() {
		if(!clientSocket.isClosed()) {
			try {
				in.close();
				out.close();
				clientSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public boolean isClosed(){
		return clientSocket.isClosed();
	}
	
	public byte readByte() {
		try {
			return in.readByte();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}
	
	public short readShort() {
		try {
			return in.readShort();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}
	
	public int readInt() throws IOException {
		return in.readInt();
	}
	
	public long readLong() throws IOException {
		return in.readLong();
	}
	
	public void readFully(byte[] b) throws IOException {
		in.readFully(b);
	}
	
	public void write(int b) throws IOException {
		if(!isClosed()){
			out.write(b);
		} 
	}
	
	public void writeShort(short s) throws IOException {
		if(!isClosed()){
			out.writeShort(s);
		} 
	}
	
	public void writeInt(int i) throws IOException {
		if(!isClosed()){
			out.writeInt(i);
		}
	}
	
	public void writeFlush() throws IOException{
		if(!isClosed()){
			out.flush();
		}
	}
}
